"""


"""
import base64
import pickle

from django_redis import get_redis_connection


# 更新redis数据库的封装
def update_redis_carts(user, sku_id, count, selected):
    redis_conn = get_redis_connection("carts")

    pipeline = redis_conn.pipeline()
    pipeline.hset("cart_%s" % user.id, sku_id, count)

    if selected:
        pipeline.sadd("selected_%s" % user.id, sku_id)

    else:
        pipeline.srem("selected_%s" % user.id, sku_id)

    pipeline.execute()


# cookie解码的封装
def get_cart_dict(cookie_data):
    cart_dict = pickle.loads(base64.b64decode(cookie_data.encode()))
    return cart_dict


# cookie编码的封装
def get_cookie_data(cart_dict):
    cookie_data = base64.b64encode(pickle.dumps(cart_dict)).decode()
    return cookie_data


# 合并购物车方法封装, 把cookies的数据覆盖redis中的数据
def merge_cart(request, user, response):

    # 获取cookies中的数据
    cookie_data = request.COOKIES.get("cart_cookies")

    if not cookie_data:
        return response

    cart_dict = get_cart_dict(cookie_data)

    # 获取redis中的数据
    redis_conn = get_redis_connection("carts")

    skus = redis_conn.hgetall("cart_%s" % user.id)

    # 写入hash变量
    # for sku_id, count in skus.items():
    #
    #     if sku_id in cart_dict:
    #
    #         count = cart_dict[sku_id]["count"]

    # 写入set
    for sku_id, sku_dict in cart_dict.items():

        redis_conn.hset("cart_%s" % user.id, sku_id, sku_dict["count"])

        if sku_dict["selected"]:
            redis_conn.sadd("selected_%s" % user.id, sku_id)

        else:
            redis_conn.srem("selected_%s" % user.id, sku_id)

    # 删除cookies
    response.delete_cookie("cart_cookies")

    return response

